﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace TemplateWeb.Helpers
{
    #region USING 
    using TemplateWeb.Models.Repositories;
    #endregion

    public class CustomAuthorizeAttribute : AuthorizeAttribute
    {
        private SLM_MembersRepository _repSLM_Members = new SLM_MembersRepository();

        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            if (AuthenticateSession())
            {
                return true;
            }
            return false;
        }

        private bool AuthenticateSession()
        {
            HttpCookie SlmSessionId = new HttpCookie("SLMFSessionId");
            SlmSessionId = HttpContext.Current.Request.Cookies["SLMFSessionId"];
            if (SlmSessionId != null && SlmSessionId.Value != "" &&
                 SlmSessionId.Value != null)
            {
                string strSessionId = SlmSessionId.Value.ToString();
                var user = _repSLM_Members.SelectByUserName(LookCookie());
                if (user != null)
                {
                    if (user.Password == strSessionId)
                    {
                        return true;
                    }
                }
                else
                {
                    return false;
                }
            }
            return false;
        }

        private string LookCookie()
        {
            HttpCookie SlmMemberCookie = new HttpCookie("SLMFMembers");
            SlmMemberCookie = HttpContext.Current.Request.Cookies["SLMFMembers"];
            string strUser = "";
            if (SlmMemberCookie != null && SlmMemberCookie.Value != "" &&
                 SlmMemberCookie.Value != null)
            {
                strUser = SlmMemberCookie.Value.ToString();
            }
            return strUser;
        }
    }
}